package com.sunseaypw.web.filter;

import com.sunseaypw.web.WebBase;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/* 过滤/hello为前缀的请求  
    filter注解中目前没有设置顺序的方法，需要在web.xml中通过声明顺序来标定执行顺序 
    最佳实践是最好不要有执行顺序上的逻辑要求，最好能不依赖顺序！！
*/
//@WebFilter(urlPatterns = "/hello/*")
@WebFilter(filterName = "Filter222") 
public class Filter222 implements Filter {
    @Override
    public void init(FilterConfig filterConfig)throws ServletException{
        System.out.println(String.format("%s Filter222-init  线程：%s",WebBase.getNowTime(), Thread.currentThread().getName()));
    }
    @Override
    public void doFilter(ServletRequest req,ServletResponse rsp,FilterChain chain)
        throws java.io.IOException, ServletException{
        System.out.println(String.format("%s Filter222-doFilter 进入  线程：%s",WebBase.getNowTime(), Thread.currentThread().getName()));        
        req.setAttribute("filter",(req.getAttribute("filter")==null?"":req.getAttribute("filter")) + "  Filter222 Filter222我来了");
        HttpServletResponse rsp111=(HttpServletResponse)rsp;
        rsp111.setHeader("content-type", "text/css");
        chain.doFilter(req,rsp);//如果Filter要使请求继续被处理，就一定要调用chain.doFilter()！
        /* doFilter后面的代码会被执行，但若后续经过forward转发后则无法写入response */    
        var url= ((HttpServletRequest)req).getRequestURL();
        if(url.indexOf("/static/")==-1){
            rsp.setContentType("text/html");
            rsp.setCharacterEncoding("utf-8");      
            var pw = rsp.getWriter();
            pw.write("<h1>filter111尾部添加点料啊!</h1>");
            pw.flush();
        }         
        System.out.println(String.format("%s Filter222-doFilter 离开 线程：%s",WebBase.getNowTime(), Thread.currentThread().getName()));                
    }
    @Override 
    public void destroy(){
        System.out.println(String.format("%s Filter222-destroy  线程：%s",WebBase.getNowTime(), Thread.currentThread().getName()));
    }
}
